package  ch.usi.inf.pf2.CSV;
import java.io.*;

import ch.usi.inf.pf2.spreadsheet.SpreadSheetCellArray;


public class FileRead {

	public static SpreadSheetCellArray readCSV (String file) {
		int row = rowCounter (file);
		int column = columnCounter(file);
		SpreadSheetCellArray spread; 
		if ((row != Message.ERROR_READING) && (column != Message.ERROR_READING)) {
			spread = new SpreadSheetCellArray(row, column);
			readFile (spread, file);
			return spread;
		} else {
			return null;
		}
		
	}
	
	private static int readFile (SpreadSheetCellArray spread, String file) {
		try {
			BufferedReader reader = new BufferedReader(new FileReader(new File (file)));
			String line;
			int row = 0;
			while ((line = reader.readLine()) != null) {
				String [] pieces = line.split(",");
				for (int column=0; column < pieces.length; column++) {
					spread.setValueAt(pieces [column], row, column);
				}
				row++;
			}
			reader.close ();
		} catch (IOException ex) {
			System.out.println("There was a problem accessing the file");
		}
		return Message.ERROR_READING;
	}
	
	private static  int columnCounter (String file) {
		try {
			BufferedReader reader = new BufferedReader(new FileReader(new File (file)));
			String line = reader.readLine();
			return line.split(",").length;
		} catch (IOException ex) {
			System.out.println("There was a problem accessing the file");
		}
		return Message.ERROR_READING;
	}
	
	private static int rowCounter (String file) {
		try {
			BufferedReader reader = new BufferedReader(new FileReader(new File(file)));
			int counter = 0;
			while (reader.readLine() != null) {
				counter++;
			}
			reader.close ();
			return counter;
		} catch (IOException ex) {
			System.out.println("There was a problem accessing the file");
		}
		return Message.ERROR_READING;
	}

}
